# -*- coding: utf-8 -*-

from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from core.serializers import CustomModelSerializer
from apps.sys.menu.serializers import MenuSerializer, MenuTreeSelectSerializer
from apps.sys.dept.serializers import DeptSerializer, DeptTreeSelectSerializer
from core.validator import CustomUniqueValidator
from core.serializers import CustomModelSerializer
from core.response import JsonResponse
from apps.sys.models import Menu, Role, Dept
from utils.tree import list2tree


class RoleSerializer(CustomModelSerializer):
    """
    角色-序列化器
    """

    class Meta:
        model = Role
        fields = "__all__"
        read_only_fields = ["id"]


class RoleMenuTreeselectSerializer(CustomModelSerializer):
    """
    树型菜单表的序列化器-角色维度
    """
    menus = serializers.SerializerMethodField(read_only=True)

    def get_menus(self, instance):
        queryset = Menu.objects.all()
        serializer = MenuTreeSelectSerializer(
            queryset, many=True, request=self.request)
        data = list2tree(serializer.data)
        return data

    class Meta:
        model = Role
        fields = "__all__"
        read_only_fields = ["id"]


class RoleDeptTreeselectSerializer(CustomModelSerializer):
    """
    树型菜单表的序列化器-角色维度
    """
    depts = serializers.SerializerMethodField(read_only=True)

    def get_depts(self, instance):
        queryset = Dept.objects.all()
        serializer = DeptTreeSelectSerializer(
            queryset, many=True, request=self.request)
        data = list2tree(serializer.data)
        return data

    class Meta:
        model = Role
        fields = "__all__"
        read_only_fields = ["id"]


class RoleCreateUpdateSerializer(CustomModelSerializer):
    """
    角色管理 创建/更新时的列化器
    """
    menu = MenuSerializer(many=True, read_only=True)
    dept = DeptSerializer(many=True, read_only=True)
    key = serializers.CharField(max_length=50, validators=[CustomUniqueValidator(
        queryset=Role.objects.all(), message="权限字符必须唯一")])
    name = serializers.CharField(max_length=50, validators=[
                                 CustomUniqueValidator(queryset=Role.objects.all())])

    def validate(self, attrs: dict):
        return super().validate(attrs)

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.dept.set(self.initial_data.get('dept', []))
        data.menu.set(self.initial_data.get('menu', []))
        return data

    class Meta:
        model = Role
        fields = '__all__'
